<template>
  <span v-if="props.showText">{{ message }}</span>
  <el-switch
    v-else-if="options.length > 1"
    v-model="dicSelect"
    inline-prompt
    :disabled="inputDisabled"
    :active-text="options[0].value"
    :active-value="options[0].key"
    :inactive-text="options[1].value"
    :inactive-value="options[1].key"
    @change="handleChange"
  ></el-switch>
</template>

<script setup>
import {ref, watch, onMounted, onUnmounted} from 'vue';
import {useDictionaryStore} from '@/pinia/modules/dictionary';
import {useDisabled} from 'element-plus';
import {emitter} from "@/utils/bus";

const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  modelValue: {
    type: [String, Boolean],
  },
  dicCode: String,
  options: Array,
  placeholder: String,
  showText: Boolean
});

const dictionaryStore = useDictionaryStore();
const options = ref([]);
const message = ref('');
const dicSelect = ref(props.modelValue);
const inputDisabled = useDisabled();

const handleChange = () => {
  emit('update:modelValue', dicSelect.value);
  emit('change');
};

const loadDicAndShow = async(dicCode) => {
  if ((dicCode || '') === '') {
    options.value = [];
  } else {
    options.value = await dictionaryStore.getDictionary(dicCode);
  }

  calcValue();
};

const calcValue = () => {
  if (options.value == null || options.value.length === 0) {
    message.value = props.modelValue;
  } else {
    let option = options.value.filter(item => item.key === dicSelect.value + '');
    if (option.length > 0) {
      message.value = option[0].value;
    } else {
      message.value = props.modelValue;
    }
  }
};

const init = (data) => {
  dicSelect.value = data.modelValue;
  if (data.options && data.options.length > 0) {
    options.value = data.options;
    calcValue();
  } else if (data.dicCode) {
    loadDicAndShow(data.dicCode);
    emitter.off('dictionary.change');
    emitter.on('dictionary.change', () => {
      loadDicAndShow(data.dicCode);
    });
  }
};

watch(() => props, (data) => {
  init(data);
}, {deep: true});

onMounted(() => {
  init(props);
});

onUnmounted(() => {
  emitter.off('dictionary.change');
});
</script>